#!/usr/bin/evn python3
# -*- coding: utf-8 -*-
import time,threading
import simpleaudio
from multiprocessing import Process, Queue

class AudioPlay(object):

    def __init__(self,data=None):
        self.mediaData = None
        self.control = None
        self.isStop = True
        if(data!=None):self.mediaData=data


    def play(self,data=None):
        #关闭上次播放的音频
        if(self.control!=None):
            self.stop()
        if(data!=None):self.mediaData=data
        # 创建一个线程并启动
        t = threading.Thread(target=self.per())
        t.start()

    def stop(self):
        self.control.stop()
        # 结束线程
        self.isStop=True

        # 音频播放线程
    def per(self):
        # 播放音频
        self.control = AudioPlay.play_with_simpleaudio(self.mediaData)
        #直到收到暂停通知
        self.isStop
        while not self.isStop and self.control.is_playing():
            time.sleep(0.05)

    @staticmethod
    def play_with_simpleaudio(seg):
        return simpleaudio.play_buffer(
            seg.raw_data,
            num_channels=seg.channels,
            bytes_per_sample=seg.sample_width,
            sample_rate=seg.frame_rate
        )

